package com.geostar.constructionland.analyse.service.handler.impl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.geostar.constructionland.analyse.entity.HttpResult;
import com.geostar.constructionland.analyse.entity.alyresult.AlyResult;
import com.geostar.constructionland.analyse.entity.alyresult.tzhdlgdfx.*;
import com.geostar.constructionland.analyse.entity.model.AnalyseModel;
import com.geostar.constructionland.analyse.entity.resulthandler.HandlerResult;
import com.geostar.constructionland.analyse.entity.statistics.SticDlfxTzh;
import com.geostar.constructionland.analyse.factory.AdjustAgrFactory;
import com.geostar.constructionland.analyse.factory.AdjustModelFactory;
import com.geostar.constructionland.analyse.service.adjust.IAdjust;
import com.geostar.constructionland.analyse.service.adjust.TzhDlGdAdjust;
import com.geostar.constructionland.analyse.service.analyseresult.TzhDlGdFxService;
import com.geostar.constructionland.analyse.service.handler.IResultHandler;
import com.geostar.constructionland.analyse.service.handler.impl.util.XmlUtil;
import com.geostar.constructionland.common.entity.response.model.AdjustModel;
import com.geostar.constructionland.common.global.ConstAnalyseType;
import com.google.common.base.VerifyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import static com.geostar.constructionland.common.global.AdjustConstant.adjustOutRange;

/**
 * @author yelll
 * @since 2020-6-9 17:24
 *
 **/
@Service(value = ConstAnalyseType.CONST_TZHDLGDFX+"Ver1.0")
@Slf4j
public class TzhDlGdHandler implements IResultHandler {
    private final static String QSXZ_NATIONAL = "国有土地所有权";
    private final static String QSXZ_GROUP = "集体土地所有权";
    private final static String QSXZ_ARGUE = "争议地";
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    TzhDlGdFxService tzhDlGdFxService;
    @Autowired
    TzhDlGdAdjust tzhDlGdAdjust;
    @Autowired
    AdjustAgrFactory adjustAgrFactory;
    @Override
    public HandlerResult handler(AnalyseModel analyseModel, HttpResult httpResult) throws Exception {
        log.info("处理调整后地类耕地分析返回数据,状态码:{}",httpResult.getCode());
        HandlerResult handlerResult = HandlerResult.createBySuccessMessage("操作无误，恭喜成功!");
        if(HttpStatus.SC_OK==httpResult.getCode()){
            /**解析xml格式,获取JSON数据**/
            String newBody = XmlUtil.parseXml(httpResult.getBody());
            httpResult.setBody(newBody);
            /**保存占压信息**/
            AlyResult alyResult = objectMapper.readValue(httpResult.getBody(),AlyResult.class);
            log.info("body:"+httpResult.getBody());
            if(HttpStatus.SC_OK == alyResult.getStatus()){
                List<AlyResultTzdDlGd> alyResultTzdDlGds = objectMapper.readValue(alyResult.getAnalysisResult().getResultRecords(),
                        new TypeReference<List<AlyResultTzdDlGd>>(){});
                /**准备数据**/
                prepareBizData(analyseModel,alyResultTzdDlGds);
                /**获取地类分析调整后统计数据**/
                List<SticDlfxTzh> sticDlfxTzhList = tzhDlGdFxService.getSticDlFxTzh(analyseModel.getAlyId());
                /**保存地类分析调整后统计数据**/
                tzhDlGdFxService.saveSticDlfxTzh(sticDlfxTzhList);
                AdjustModel adjustModel = AdjustModelFactory.getAdjustModByAnalyse(analyseModel);
                IAdjust adjust = adjustAgrFactory.getAdjustAgrByAnalyseModel(analyseModel.getFxlxMapped());
                adjust.adjust(adjustModel);
            }
            else{
                throw new Exception(alyResult.getMessage());
            }
        }else {
            handlerResult = HandlerResult.createBySpatiaAnalyse_error("调用分析失败，请查看分析结果内容",httpResult);
        }
        return handlerResult;
    }



    /***
     * 准备数据
     * @param analyseModel 分析输入实体
     * @param alyResultTzdDlGds 调整后地类耕地分析结果
     */
    public void prepareBizData(AnalyseModel analyseModel,List<AlyResultTzdDlGd> alyResultTzdDlGds){
        List<AlyResultZdxx> zdxxList = new ArrayList<>();
        List<AlyResultQlxx> qlxxList = new ArrayList<>();
        List<AlyResultDlfx> dlfxList = new ArrayList<>();
        List<AlyResultXzdw> xzdwList = new ArrayList<>();
        List<AlyResultGdZlDb> gdZlDbList = new ArrayList<>();

        Map qsMap = new HashMap();
        alyResultTzdDlGds.forEach(alyResultTzdDlGd -> {
            /**构建宗地信息**/
            String zdxxId = UUID.randomUUID().toString().replace("-","");
            /**宗地代码**/
            String zddm = alyResultTzdDlGd.getZddm();
            /**不动产单元号**/
            String bdcdyh = alyResultTzdDlGd.getBdcdyh();
            /**确定权属性质**/
            String qsxz = "";
            if(StringUtils.isBlank(alyResultTzdDlGd.getQsxz()) || QSXZ_NATIONAL.equals(alyResultTzdDlGd.getQsxz())){
                qsxz = "20";
            }else if(QSXZ_GROUP.equals(alyResultTzdDlGd.getQsxz()) || QSXZ_ARGUE.equals(alyResultTzdDlGd.getQsxz())){
                qsxz = "30";
            }else {
                log.error("权属性质：{}",alyResultTzdDlGd.getQsxz());
                throw new VerifyException("接口传回的权属性质无法解析:{}"+alyResultTzdDlGd.getQsxz());
            }
            /**保存宗地逻辑,宗地代码以及不动产单元号**/
            if(StringUtils.isNotBlank(zddm) && qsMap.containsKey(zddm)){
                zdxxId = qsMap.get(zddm).toString();
            }else if(StringUtils.isNotBlank(bdcdyh) && qsMap.containsKey(bdcdyh)){
                zdxxId = qsMap.get(bdcdyh).toString();
            }else if(StringUtils.isBlank(zddm) && StringUtils.isBlank(bdcdyh) && qsMap.containsKey(null)){
                zdxxId = qsMap.get(null).toString();
            }else {
                /***构建权属对象**/
                qsMap.put(zddm,zdxxId);
                qsMap.put(bdcdyh,zdxxId);
                AlyResultZdxx alyResultZdxx = new AlyResultZdxx();
                alyResultZdxx.setFxid(zdxxId);
                alyResultZdxx.setZddm(zddm);
                alyResultZdxx.setBdcdyh(bdcdyh);
                alyResultZdxx.setZdmj(alyResultTzdDlGd.getZdmj());
                alyResultZdxx.setQsxz(qsxz);
                alyResultZdxx.setFxbs(analyseModel.getAlyId());
                alyResultZdxx.setCzlx("zy");
                alyResultZdxx.setQlxz(StringUtils.isBlank(alyResultTzdDlGd.getQsxz())?
                        QSXZ_NATIONAL:alyResultTzdDlGd.getQsxz());
                zdxxList.add(alyResultZdxx);
                /**构建权利信息**/
                AlyResultQlxx alyResultQlxx = new AlyResultQlxx();
                alyResultQlxx.setFxid(UUID.randomUUID().toString().replace("-",""));
                alyResultQlxx.setTdzh(alyResultTzdDlGd.getTdzh());
                alyResultQlxx.setQlrmc(alyResultTzdDlGd.getQlrmc());
                alyResultQlxx.setFzsj(alyResultTzdDlGd.getFzsj());
                alyResultQlxx.setFzmj(alyResultTzdDlGd.getFzmj());
                alyResultQlxx.setBdcqzh(alyResultTzdDlGd.getBdcqzh());
                alyResultQlxx.setZdxxid(zdxxId);
                alyResultQlxx.setFxbs(analyseModel.getAlyId());
                qlxxList.add(alyResultQlxx);
            }
            /**构建地类数据**/
            AlyResultDlfx alyResultDlfx = new AlyResultDlfx();
            String dlid = UUID.randomUUID().toString().replace("-","");
            alyResultDlfx.setDlid(dlid);
            alyResultDlfx.setDkbs(alyResultTzdDlGd.getDkbs());
            alyResultDlfx.setDlbm(alyResultTzdDlGd.getDlbm());
            alyResultDlfx.setDlmj(alyResultTzdDlGd.getTbmj());
            alyResultDlfx.setTbdlmj(alyResultTzdDlGd.getTbdlmj());
            alyResultDlfx.setTkmj(alyResultTzdDlGd.getTkmj());
            alyResultDlfx.setKcdlbm(alyResultTzdDlGd.getKcdlbm().trim());
            alyResultDlfx.setXzdwmj(alyResultTzdDlGd.getKcmj());
            alyResultDlfx.setZdxxid(zdxxId);
            alyResultDlfx.setBphxfxid(alyResultTzdDlGd.isSfyphx()+"");
            alyResultDlfx.setDllx("占压");
            alyResultDlfx.setFxbs(analyseModel.getAlyId());
            alyResultDlfx.setKtzmj(alyResultTzdDlGd.isSfktz()?1:0);
            dlfxList.add(alyResultDlfx);
            List<AlyResultXzdw> xzdwList_target = alyResultTzdDlGd.getAlyResultXzdws();
            /**构建线状地物**/
            for(int i = 0 ; i < xzdwList_target.size() ; i++ ){
                AlyResultXzdw alyResultXzdw = xzdwList_target.get(i);
                alyResultXzdw.setXzdwid(UUID.randomUUID().toString().replace("-",""));
                alyResultXzdw.setQsdwmc1(dlid);
                alyResultXzdw.setZymj(alyResultXzdw.getLlxzdwmj());
                alyResultXzdw.setFxbs(analyseModel.getAlyId());
                alyResultXzdw.setDkbs(alyResultTzdDlGd.getDkbs());
                alyResultXzdw.setZdxxid(zdxxId);
                alyResultXzdw.setBphxfxid(alyResultTzdDlGd.isSfyphx()+"");
                xzdwList.add(alyResultXzdw);
            }
            List<AlyResultGdZlDb> gdZlDbList_target = alyResultTzdDlGd.getAlyResultGdZlDbs();

            /***构建耕地分析数据**/
            for(int idx = 0 ; idx < gdZlDbList_target.size() ; idx++){
                AlyResultGdZlDb alyResultGdZlDb = gdZlDbList_target.get(idx);
                alyResultGdZlDb.setFxid(UUID.randomUUID().toString().replace("-",""));
                alyResultGdZlDb.setDlid(dlid);
                alyResultGdZlDb.setDkbs(alyResultTzdDlGd.getDkbs());
                alyResultGdZlDb.setFxbs(analyseModel.getAlyId());
                alyResultGdZlDb.setDbmj(alyResultTzdDlGd.getTbmj());
                alyResultGdZlDb.setZymj(new BigDecimal(alyResultGdZlDb.getTbdlmj()).setScale(0,BigDecimal.ROUND_HALF_UP).doubleValue());
                alyResultGdZlDb.setDltbdlbm(alyResultTzdDlGd.getDlbm());
                gdZlDbList.add(alyResultGdZlDb);
            }
        });
        /**统计部分数据**/
        tzhDlGdFxService.saveAlyResultZdxxs(zdxxList);
        tzhDlGdFxService.saveAlyResultQlxxs(qlxxList);
        tzhDlGdFxService.saveAlyResultDlfx(dlfxList);
        tzhDlGdFxService.saveAlyResultXzdws(xzdwList);
        tzhDlGdFxService.saveAlyResultGdZldbs(gdZlDbList);
    }
}
